package code.lucamarrocco.rest;

import static code.lucamarrocco.rest.Matchers.*;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class RestfulProtocolMather {
	public static final RestfulProtocolMather matcher(RestfulProtocol protocol) {
		return new RestfulProtocolMather().using(protocol);
	}

	private List<String> matchers = new LinkedList<String>();

	private Map<String, RestfulMethod> methods = new LinkedHashMap<String, RestfulMethod>();

	public RestfulProtocolMather() {}

	public boolean matches(String uri) {
		for (String matcher : matchers)
			if (uri.matches(matcher)) return true;

		return false;
	}

	public RestfulMethod method(String uri) {
		for (String matcher : matchers) {
			if (uri.matches(matcher)) {
				return apply(uri, methods.get(matcher));
			}
		}
		return null;
	}

	public String signatureOf(String uri) {
		return Signatures.topicSignatureOf(method(uri));
	}

	public RestfulProtocolMather using(RestfulProtocol protocol) {
		matchers = new LinkedList<String>();
		for (RestfulMethod method : protocol.getMethods()) {
			for (String methodMatcher : matchersOf(method)) {
				matchers.add(methodMatcher);
				methods.put(methodMatcher, method);
			}
		}
		return this;
	}
}
